package com.wcity.manage.service.impl;

import com.wcity.manage.common.utils.AuthUtil;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.mapper.RoleMapper;
import com.wcity.manage.dao.model.Role;
import com.wcity.manage.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色服务层
 *
 * @author dy
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Override
    public List<Role> getRoleList(Role role ) {
        return roleMapper.findList(role);
    }

    @Override
    public List<Role> getRoleListPage( PageModel<Role> page ) {
        return roleMapper.findListPage( page );
    }

    @Override
    public Role getRole( int id ) {
        return roleMapper.find( id );
    }

    @Override
    public String addRole( Role role, List<Integer> authIds ) {

        Role local = roleMapper.findByRoleName( role.getRoleName() );
        if ( local != null ) return "角色已存在";

        role = authorize( authIds, role );
        try {
            if ( roleMapper.insert( role ) <= 0 ) return "添加用户失败";
        } catch ( DataAccessException e ) {
            log.error( "addRole error, {}", e.getMessage(), e );
            return "添加角色失败";
        }
        return "";
    }

    @Override
    public String updateRole( Role role, int id, List<Integer> authIds ) {
        role.setId( id );
        role = authorize( authIds, role );
        try {
            if ( roleMapper.update( role ) <= 0 ) return "没有更新";
        } catch ( DataAccessException e ) {
            log.error( "updateRole error, {}", e.getMessage(), e );
            return "更新角色失败";
        }
        return "";
    }

    /**
     * 授权
     *
     * @param authIds
     * @param role
     * @return
     */
    private Role authorize( List<Integer> authIds, Role role ) {
        AuthUtil.authorize( authIds, role );
        return role;
    }

    @Resource private RoleMapper roleMapper;

    private final static Logger log = LoggerFactory.getLogger( RoleServiceImpl.class );

}
